cd "C:\Users\Public\Documents\ImmPanelRevis19\"
cd "ImmPanelRevis19\Donnees\select"

/****************************/
/* LONG DISTANCE DAILY WAGE */
/******************************************/
/* interaction term model for daily wages */
/*******************************************/
capture program drop wagesinter
program define wagesinter
version 11
syntax, occp(name) 

/********************/
/* Balanced Sample  */
/********************/
use final.dta, clear

/* keep individuals in the occupation group */
keep if (btime==1 & `occp') | (btime==2 & L.`occp')

/* location in the decile of the initial group distribution */
gen lsnd=ln(sn/dp)
/* residual wages for each year */
quietly: reg lsnd F_* 
predict rlsnd, residuals
/* change in residual wages */
gen drlsnd=D.rlsnd

/* region of residence */
joinby depr using tp1.dta, unm(m)
tab _merge 
drop _merge

joinby adepr using tp2.dta, unm(m)
tab _merge 
drop _merge

/* change commuting zones AND region of residency */
/*gen lshiftr=(ze!=aze & regr!=aregr)*/
gen lshiftr=(ze!=aze & depr!=adepr)

/* change commuting zones AND SAME region of residency */
/*gen lshiftsr=(ze!=aze & regr==aregr)*/
gen lshiftsr=(ze!=aze & depr==adepr)

gen oshift=(`occp'==0 & L.`occp'==1)
keep if btime==2 & L.`occp' & !missing(dimm) & !missing(dimm75)
foreach year in 1982 1991 1999 2007 {
/* winsorize drlsnd */
quietly: sum drlsnd if an==`year', d
replace drlsnd=. if drlsnd>`r(p99)' & an==`year'
replace drlsnd=. if drlsnd<`r(p1)' & an==`year'
}
drop if missing(drlsnd)
drop if missing(basman)
drop if missing(bascom)

/* weight inverse of the size of the group in the CZ */
save temp.dta, replace
gen dummy=1
collapse (sum) nbze = dummy , by(ze an)
gen iw2=1/ nbze
drop nbze

save iw2.dta, replace
use temp.dta, replace
capture drop _merge
joinby ze an using iw2.dta , unm(m)
drop _merge

gen shinter=dimm*lshift
gen shinter75=dimm75*lshift

gen shinterr=dimm*lshiftr
gen shinterr75=dimm75*lshiftr

gen shintersr=dimm*lshiftsr
gen shintersr75=dimm75*lshiftsr

ivreg2 drlsnd (dimm  = dimm75 ) Y_* [aweight = iw2] , cl(ze) partial(Y_*)
estimates store c1

ivreg2 drlsnd (dimm shinter  = dimm75 shinter75 ) lshift Y_* [aweight = iw2] , cl(ze) partial(Y_*)
estimates store c2

ivreg2 drlsnd (dimm shinterr shintersr  = dimm75 shinterr75  shintersr75) lshiftr lshiftsr Y_* [aweight = iw2] , cl(ze) partial(Y_*)
estimates store c3

estout c1 c2 c3, cells(b(star fmt(%9.3f)) ///
se(par(`"="("'`")""'))) stats(N r2 rkf) starlevels(* 0.10 ** 0.05 *** 0.01)

esttab c1 c2 c3 ///
using "C:\Users\Public\Documents\Tab21\TableA15.rtf" /// 
, append title("`occp'")  b(%9.3f) cells(b(star fmt(3)) se(fmt(3) par) ) ///
 stats(N widstat) star(* 0.10 ** 0.05 *** 0.01)
end

capture rm "C:\Users\Public\Documents\Tab21\TableA15.rtf"

wagesinter, occp(bc) 
wagesinter, occp(bcnq) 
 